package edu.uwosh.cs342.group1.database;

import java.io.*;
import java.net.*;
import java.util.*;

import edu.uwosh.cs342.group1.storage.*;

public class DbCloud {
	public static final String CLOUD_LOCATION = "http://cs346.cs.uwosh.edu/students/blairm83/cs342group1/";
    public static final int bufferSize = 1024;
    
    /**
     * Adds a new user to the database
     * @param user
     * @return
     */
    public Boolean AddNewUser(CloudUser user) {
    	URL login = null;
    	try {
    		login = new URL(CLOUD_LOCATION + "addUser.php?user=" + user.getUsername() + "&pass=" + CloudUser.EncryptPassword(user.getPassword()));
    	}
    	catch(MalformedURLException e) {
    		System.out.println("Bad URL Found");
    		return false;
    	}
    	catch (Exception e) {
    		System.out.println("Some bad stuff happened: " + e.getStackTrace() == null ? " Cause unknown" : e.getStackTrace());
    		return false;
    	}
    	
    	String result = "false";
    	
    	try {
	    	HttpURLConnection conn = (HttpURLConnection)login.openConnection();
	    	HttpURLConnection.setFollowRedirects(false);
	    	conn.setConnectTimeout(5000);
	    	conn.setReadTimeout(5000);
	    	BufferedReader in = new BufferedReader(
	    							new InputStreamReader(
	    							conn.getInputStream()));
	    	String inputLine;
	
	    	if ((inputLine = in.readLine()) != null) {
	    		result = inputLine;
	    	}
	    	
	    	in.close();
    	}
    	catch (UnknownHostException e) {
    		System.out.println("The web service could not connect.");
    		return false;
    	}
    	catch (IOException e) {
    		System.out.println ("IO Exception found");
    		return false;
    	}
    	
		return result.equals("true");
    }
    
    /**
     * Updates the user's password
     * @param user
     * @param newPassword
     * @return
     */
    public Boolean UpdateUser(CloudUser user, String newPassword) {
    	URL login = null;
    	try {
    		login = new URL(CLOUD_LOCATION + "updateUser.php?user=" + user.getUsername() + "&oldPass=" + CloudUser.EncryptPassword(user.getPassword()) + "&newPass=" + CloudUser.EncryptPassword(newPassword));
    	}
    	catch(MalformedURLException e) {
    		System.out.println("Bad URL Found");
    		return false;
    	}
    	catch (Exception e) {
    		System.out.println("Some bad stuff happened: " + e.getStackTrace() == null ? " Cause unknown" : e.getStackTrace());
    		return false;
    	}

    	String result = "false";
    	
    	try {
	    	HttpURLConnection conn = (HttpURLConnection)login.openConnection();
	    	HttpURLConnection.setFollowRedirects(false);
	    	conn.setConnectTimeout(5000);
	    	conn.setReadTimeout(5000);
	    	BufferedReader in = new BufferedReader(
	    							new InputStreamReader(
	    							conn.getInputStream()));
	    	String inputLine;
	    	
	    	if ((inputLine = in.readLine()) != null) {
	    		result = inputLine;
	    	}
	    	
	    	in.close();
    	}
    	catch (UnknownHostException e) {
    		System.out.println("The web service could not connect.");
    		return false;
    	}
    	catch (IOException e) {
    		System.out.println ("IO Exception found");
    		return false;
    	}
    	
    	return result.equals("true");
    }
    
	/**
	 * Calls the PHP service to authenticate the user
	 * @param user
	 * @return
	 */
	public Boolean AuthenticateUser(CloudUser user) {
		URL login = null;
    	try {
    		login = new URL(CLOUD_LOCATION + "authenticateUser.php?user=" + user.getUsername() + "&pass=" + CloudUser.EncryptPassword(user.getPassword()));
    	}
    	catch(MalformedURLException e) {
    		System.out.println("Bad URL Found");
    		return false;
    	}
    	catch (Exception e) {
    		System.out.println("Some bad stuff happened: " + e.getStackTrace() == null ? " Cause unknown" : e.getStackTrace());
    		return false;
    	}
    	
    	int count = 0;
    	
    	try {
	    	HttpURLConnection conn = (HttpURLConnection)login.openConnection();
	    	HttpURLConnection.setFollowRedirects(false);
	    	conn.setConnectTimeout(5000);
	    	conn.setReadTimeout(5000);
	    	BufferedReader in = new BufferedReader(
	    							new InputStreamReader(
	    							conn.getInputStream()));
	    	String inputLine;
	
	    	if ((inputLine = in.readLine()) != null) {
	    		count = Integer.parseInt(inputLine);
	    	}
	    	
	    	in.close();
    	}
    	catch (UnknownHostException e) {
    		System.out.println("The web service could not connect.");
    		return false;
    	}
    	catch (IOException e) {
    		System.out.println ("IO Exception found");
    		return false;
    	}
    	
		return (count > 0);
	}

	/**
	 * Gets the list of available quizzes for the user
	 * @param username
	 * @return
	 */
	public List<Quiz> GetAvailableQuizzes(String username) {
    	URL login = null;
    	List<Quiz> quizzes = new ArrayList<Quiz>();
    	try {
    		login = new URL(CLOUD_LOCATION + "getAllQuizzes.php?user=" + username);
    	}
    	catch(MalformedURLException e) {
    		System.out.println("Bad URL Found");
    		return null;
    	}
    	catch (Exception e) {
    		System.out.println("Some bad stuff happened: " + e.getStackTrace() == null ? " Cause unknown" : e.getStackTrace());
    		return null;
    	}
    	    	
    	try {
	    	HttpURLConnection conn = (HttpURLConnection)login.openConnection();
	    	HttpURLConnection.setFollowRedirects(false);
	    	conn.setConnectTimeout(5000);
	    	conn.setReadTimeout(5000);
	    	BufferedReader in = new BufferedReader(
	    							new InputStreamReader(
	    							conn.getInputStream()));
	    	String inputLine;
	
	    	while ((inputLine = in.readLine()) != null) {
	    		Quiz quiz = new Quiz();
	    		int divisor = inputLine.indexOf("\t");
	    		quiz.setId(Integer.parseInt(inputLine.substring(0, divisor)));
	    		quiz.setName(inputLine.substring(divisor + 1));
	    		quizzes.add(quiz);
	    	}
	    	
	    	in.close();
    	}
    	catch (UnknownHostException e) {
    		System.out.println("The web service could not connect.");
    		return null;
    	}
    	catch (IOException e) {
    		System.out.println ("IO Exception found");
    		return null;
    	}
    	
		return quizzes;
	}
	
	/**
	 * Gets the quiz for the user, and decrypts the XML
	 * @param id
	 * @return
	 */
	public String GetQuiz(int id) {
		BufferedInputStream input=null;
        URL url = null;
        String xml = "";
        try {
            url = new URL(CLOUD_LOCATION + "getQuiz.php?id=" + id);
            input = new BufferedInputStream((url.openStream()));
            
            byte[] buffer = new byte[bufferSize];
            int length, numberOfBytesCopied = 0;
            while ((length = input.read(buffer, 0, bufferSize)) != -1) {
                 xml += new String(buffer,0,length);
                 numberOfBytesCopied += length;
            }
            
            System.out.println(numberOfBytesCopied +" bytes retrieved");
            if (input != null) {
            	input.close(); 
            }
        }
        catch (MalformedURLException e) {
        	System.out.println("URL incorrectly formed");
        	return null;
        } 
        catch (EOFException e) {
        	return null;
        }
        catch(IOException e) {
        	System.out.println(e.getMessage());
        	return null;
        }
        
	    return xml.trim();
	}
	
	/**
	 * Submits the user's score
	 * @param score
	 * @return
	 */
	public Boolean SubmitScore(Scores score) {
		URL login = null;
    	try {
    		System.out.println(score.getUsername());
    		login = new URL(CLOUD_LOCATION + "submitScore.php?user=" + score.getUsername() + "&score=" + Scores.EncryptScore(score.getScore()) + "&quizId=" + score.getQuiz().getId() + "&isShown=" + score.getIsPublic());
    	}
    	catch(MalformedURLException e) {
    		System.out.println("Bad URL Found");
    		return false;
    	}
    	catch (Exception e) {
    		System.out.println("Some bad stuff happened: " + e.getStackTrace() == null ? " Cause unknown" : e.getStackTrace());
    		return false;
    	}
    	
    	String result = "false";
    	
    	try {
	    	HttpURLConnection conn = (HttpURLConnection)login.openConnection();
	    	HttpURLConnection.setFollowRedirects(false);
	    	conn.setConnectTimeout(5000);
	    	conn.setReadTimeout(5000);
	    	BufferedReader in = new BufferedReader(
	    							new InputStreamReader(
	    							conn.getInputStream()));
	    	String inputLine;
	
	    	if ((inputLine = in.readLine()) != null) {
	    		result = inputLine;
	    	}
	    	
	    	in.close();
    	}
    	catch (UnknownHostException e) {
    		System.out.println("The web service could not connect.");
    		return false;
    	}
    	catch (IOException e) {
    		System.out.println ("IO Exception found");
    		return false;
    	}
    	
		return result.equals("true");
	}
	
	/**
	 * Gets the top 10 user's scores
	 * @param username
	 * @return
	 */
	public List<Scores> GetUserScores(String username) {
    	URL login = null;
    	List<Scores> scores = new ArrayList<Scores>();
    	try {
    		login = new URL(CLOUD_LOCATION + "getUserScores.php?user=" + username);
    	}
    	catch(MalformedURLException e) {
    		System.out.println("Bad URL Found");
    		return null;
    	}
    	catch (Exception e) {
    		System.out.println("Some bad stuff happened: " + e.getStackTrace() == null ? " Cause unknown" : e.getStackTrace());
    		return null;
    	}
    	    	
    	try {
	    	HttpURLConnection conn = (HttpURLConnection)login.openConnection();
	    	HttpURLConnection.setFollowRedirects(false);
	    	conn.setConnectTimeout(5000);
	    	conn.setReadTimeout(5000);
	    	BufferedReader in = new BufferedReader(
	    							new InputStreamReader(
	    							conn.getInputStream()));
	    	String inputLine;
	
	    	while ((inputLine = in.readLine()) != null) {
	    		Scores score = new Scores();
	    		int divisor = inputLine.indexOf("\t");
	    		score.setUsername(inputLine.substring(0, divisor));
	    		int divisor2 = (inputLine.substring(divisor + 1)).indexOf("\t") + (divisor + 1);
	    		score.setScore(Scores.DecryptScore(inputLine.substring(divisor + 1, divisor2)));
	    		Quiz quiz = new Quiz();
	    		quiz.setName(inputLine.substring(divisor2 + 1));
	    		score.setQuiz(quiz);
	    		scores.add(score);
	    	}
	    	
	    	in.close();
    	}
    	catch (UnknownHostException e) {
    		System.out.println("The web service could not connect.");
    		return null;
    	}
    	catch (IOException e) {
    		System.out.println ("IO Exception found");
    		return null;
    	}
    	
		return scores;
	}
	
	/**
	 * Gets the top 10 scores for all users
	 * @return
	 */
	public List<Scores> GetAllScores() {
		URL login = null;
    	List<Scores> scores = new ArrayList<Scores>();
    	try {
    		login = new URL(CLOUD_LOCATION + "getAllScores.php");
    	}
    	catch(MalformedURLException e) {
    		System.out.println("Bad URL Found");
    		return null;
    	}
    	catch (Exception e) {
    		System.out.println("Some bad stuff happened: " + e.getStackTrace() == null ? " Cause unknown" : e.getStackTrace());
    		return null;
    	}
    	    	
    	try {
	    	HttpURLConnection conn = (HttpURLConnection)login.openConnection();
	    	HttpURLConnection.setFollowRedirects(false);
	    	conn.setConnectTimeout(5000);
	    	conn.setReadTimeout(5000);
	    	BufferedReader in = new BufferedReader(
	    							new InputStreamReader(
	    							conn.getInputStream()));
	    	String inputLine;
	
	    	while ((inputLine = in.readLine()) != null) {
	    		Scores score = new Scores();
	    		int divisor = inputLine.indexOf("\t");
	    		score.setUsername(inputLine.substring(0, divisor));
	    		int divisor2 = (inputLine.substring(divisor + 1)).indexOf("\t") + (divisor + 1);
	    		score.setScore(Scores.DecryptScore(inputLine.substring(divisor + 1, divisor2)));
	    		Quiz quiz = new Quiz();
	    		quiz.setName(inputLine.substring(divisor2 + 1));
	    		score.setQuiz(quiz);
	    		scores.add(score);
	    	}
	    	
	    	in.close();
    	}
    	catch (UnknownHostException e) {
    		System.out.println("The web service could not connect.");
    		return null;
    	}
    	catch (IOException e) {
    		System.out.println ("IO Exception found");
    		return null;
    	}
    	
		return scores;
	}
}
